import Serv from './gameServ';
var regeneratorRuntime = require("../../../../lib/js/runtime-module.js");
var sensorsdata_conf = require("../../../../utils/sensorsdata_conf.js")
import Config from '../../../../utils/config2.js'
import cardConfig from '../../../../config.js'
import formatDate from '../../../../utils/util2.js'

var app = getApp()
Page({

  /** 
   * 页面的初始数据
   */
  data: {
    //文字跑马灯参数
    broadcast_arr: {
      speed: 2.8, //滚动速度，每秒2.8个字
      font_size: "13", //字体大小(px)
    },
    isShowWinModal:false,//是否显示中奖或不中奖模态框
    // showPrizeTipModal:false,//是否显示领奖提示
    recommendData:[],//推荐楼房
    nickName: '',//用户昵称
    headPortraitUrl: '',//用户头像
    mobilePhone:"",//用户电话号码
    countDown:true,//活动倒计时状态
    gameActivityId:"",//页面传值，活动ID
    activityUser: {//当前用户信息
      remainLuckDrawNumber:0,//剩余次数
      luckDrawFlag:0,//当前用户是否有资格抽奖状态
    },
    gamePrizeData:{},//游戏中奖后的奖品信息对象
    djsTime:null,//倒计时定时
    gameBaseData: {//游戏界面后台接口对象
      title:'',
      titleImgUrl:'',
      nowTime:'',//当天服务器时间
      endTime:'',//活动结束时间
      day: 0,//天数
      hou: 0,//小时
      min: 0,//分钟
      sec: 0,//秒
      virtualNumber: 0,//虚拟参与人数
      actualNumber: 0,//实际参与人数
    },
    isOpenHelpModal:false,//是否打开了好友助力模态框
    gameHighSetData:{},
    gameResultData: {},//游戏结果列表
    winnersData:[],//获奖名单
    bg: "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_machine_bg.png",
    // 抽奖button状态
    drawId: 0, 
    showDefault: false,
    showdraw:false,
    winStatus:'-2',//-2：没开始游戏;-1：游戏进行中；0：未中奖；1：中奖；
    itemImgs: [//默认图片列表
    {
      id: 1,
      url: "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M1.png"
    }, {
      id: 2,
        url: "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M2.png"
    }, {
      id: 3,
        url: "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M3.png"
    }, {
      id: 4,
        url: "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M4.png"
      }, {
        id:5,
        url: "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M5.png"
      }, {
        id: 6,
        url: "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M6.png"
      }
    ],
    tab1: { // 第一列当前显示的图片
      id: 1,
      url: "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M1.png"
    },
    tab2: { // 第二列当前显示的图片
      id: 2,
      url: "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M2.png"
    },
    tab3: { // 第三列当前显示的图片
      id: 3,
      url: "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M4.png"
    },
    tab4: { 
      id: 4,
      url: "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M4.png"
    },
    tab5: { // 第二列当前显示的图片
      id: 5,
      url: "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M5.png"
    },
    tab6: { // 第三列当前显示的图片
      id: 6,
      url: "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M4.png"
    },
    tab7: {
      id: 7,
      url: "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M4.png"
    },
    tab8: { // 第二列当前显示的图片
      id: 8,
      url: "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M5.png"
    },
    tab9: { // 第三列当前显示的图片
      id: 9,
      url: "https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/games/game_M4.png"
    },
    animationData1: {}, // 第一列动画
    animationData2: {}, // 第二列动画
    animationData3: {}, // 第三列动画

    animationData4: {}, // 第一列动画
    animationData5: {}, // 第二列动画
    animationData6: {}, // 第三列动画

    animationData7: {}, // 第一列动画
    animationData8: {}, // 第二列动画
    animationData9: {}, // 第三列动画
    // animationData4: {}, // 第三列动画
  },
  /* 
   *初始化加载数据
   */
  onLoad(options) {
    wx.hideShareMenu();
    let userData = wx.getStorageSync('userData');
    let userInfo = wx.getStorageSync('userInfo');
    this.setData({
      gameActivityId:options.gameActivityId,
      mobilePhone: userData.mobile,
      nickName: userInfo.nickName,
      headPortraitUrl: userData.avatarUrl
    });
  },
  onShow(){
    if(!app.globalData.isAddUserSuccess){
      app.addUser(this.data.gameActivityId)
    }
     //获取游戏的基础设置信息
     this.getBaseData();
     //获取游戏高级设置信息
     this.getHighSetData();
     //获取当前活动中奖信息列表
     this.getWinnerUserList();
     //获取当前用户信息
     this.getActivityUser();
  },
  //预加载海报图片
  preload: function () {
    let { gameHighSetData } = this.data;
    var userInfoData = wx.getStorageSync('userInfoData')
    var userInfo = wx.getStorageSync('userInfo')
    let bg = [`${(gameHighSetData && gameHighSetData.posterImgUrl) ? gameHighSetData.posterImgUrl : ''}`, userInfoData.headImgUrl || userInfo.avatarUrl];
    // //debugger
    formatDate.imgPreLoad(bg, (preLoadImg) => {
      wx.setStorageSync('preLoadImg', preLoadImg)
    })
  },

  formSubmitList(e){
    let productid = e.detail.target.dataset.productid
    sensorsdata_conf.server_url = `${Config.host}app/dataAnalysis/create`
    app.globalData.sensors.setPara(sensorsdata_conf);
    app.globalData.sensors.track('gameEvent', {gameActivityId: this.data.gameActivityId,productId:productid});
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    clearTimeout(this.data.djsTime);
    clearTimeout(this.data.t1);
    clearTimeout(this.data.t2);
    clearTimeout(this.data.t3);
    clearTimeout(this.data.t4);
    clearTimeout(this.data.t5);
    clearTimeout(this.data.t6);
    clearTimeout(this.data.t7);
    clearTimeout(this.data.t8);
    clearTimeout(this.data.t9);
    clearTimeout(this.data.t10);
    clearTimeout(this.data.t11);
    clearTimeout(this.data.t12);
    sensorsdata_conf.server_url = `${cardConfig.config.pageDomain}applet/visitLog/create`
    app.globalData.sensors.setPara(sensorsdata_conf);
  },
    /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearTimeout(this.data.djsTime);
    clearTimeout(this.data.t1);
    clearTimeout(this.data.t2);
    clearTimeout(this.data.t3);
    clearTimeout(this.data.t4);
    clearTimeout(this.data.t5);
    clearTimeout(this.data.t6);
    clearTimeout(this.data.t7);
    clearTimeout(this.data.t8);
    clearTimeout(this.data.t9);
    clearTimeout(this.data.t10);
    clearTimeout(this.data.t11);
    clearTimeout(this.data.t12);
    sensorsdata_conf.server_url = `${cardConfig.config.pageDomain}applet/visitLog/create`
    app.globalData.sensors.setPara(sensorsdata_conf);
  },
  //中奖名单跑马灯轮播
  scrolltxt: function () {
    let ititdata = this.data.winnersData,
      assist = this.data.broadcast_arr,
      this_width = 0,
      spacing = 0,
      speed = (this.data.broadcast_arr.speed * this.data.broadcast_arr.font_size); //m每秒行走的距离

    for (let i in ititdata) {
      ititdata[i].starspos = wx.getSystemInfoSync().windowWidth; //以取屏幕宽度为间距
      this_width += (ititdata[i].nickname.length + "恭喜中了".length + ititdata[i].awardName.length) * this.data.broadcast_arr.font_size;
      if (i != ititdata.length - 1) {
        spacing += ititdata[i].starspos
      }
    }
    let total_length = this_width + spacing;//总长
    assist.time = total_length / speed; /**滚动时间*/
    assist.width_mal = total_length;
    this.setData({
      broadcast_arr: assist,
      winnersData: ititdata
    })
  },
  // catchTouchMove: function (res) {
  //   return false;
  // },
  hideModal:function(){
    this.setData({
      winStatus: '-1'
    });
  },
  showHelpModal: function () {
    let that = this;
    if (that.data.gameHighSetData.allowSharing == 0 && that.data.gameHighSetData.sharingPosterShow == 0){
      if (that.data.gameHighSetData.assistedOpening == 0){
        wx.showToast({
          title: '本活动暂不支持助力。',
          icon: "none",
          duration: 2000
        });
      }
    }else{
      this.setData({
        isOpenHelpModal: true
      });
      wx.showShareMenu();
    }
  },
  hideHelpModal: function () {
    this.setData({
      isOpenHelpModal: false
    });
    wx.hideShareMenu();
  },
  getWin:function(){
    let activityUser = this.data.activityUser;
    if (activityUser.remainLuckDrawNumber && activityUser.remainLuckDrawNumber > 0) {
      activityUser.remainLuckDrawNumber = activityUser.remainLuckDrawNumber - 1;
      if (activityUser.remainLuckDrawNumber > 0) {
        this.setData({
          activityUser: activityUser,
          drawId: 1
        });
      } else {
        activityUser.remainLuckDrawNumber = 0;
        this.setData({
          activityUser: activityUser,
          drawId: 0
        });
      }
    }
    this.setData({
      winStatus:'1' 
    });
  },
  getNoWin: function () {
    let activityUser = this.data.activityUser;
    if (activityUser.remainLuckDrawNumber > 0) {
      activityUser.remainLuckDrawNumber = activityUser.remainLuckDrawNumber - 1;
      if (activityUser.remainLuckDrawNumber > 0) {
        this.setData({
          activityUser: activityUser,
          drawId: 1
        });
      } else {
        activityUser.remainLuckDrawNumber = 0;
        this.setData({
          activityUser: activityUser,
          drawId: 0
        });
      }
    }
    this.setData({
      winStatus: '0'
    });
  },
  /* 
   *"抽奖点击事件"
   */
  getAnmiation: function () {
    var page = this;
    let that = this
    if (page.data.drawId != 1){
      let activityUser = page.data.activityUser;
      if (activityUser.luckDrawFlag == 0){
        if(that.data.gameHighSetData.assistedOpening == 0){
          wx.showToast({
            title: '你没有抽奖机会了。',
            icon:"none",
            duration: 2000
          });
        }else{
          wx.showToast({
            title: '您没有抽奖机会了，请先分享链接让好友助力后，再参与抽奖。',
            icon:"none",
            duration: 2000
          });
        }
      } else if (activityUser.luckDrawFlag != 0) {
        if (activityUser.remainLuckDrawNumber <= 0) {
          wx.showToast({
            title: '您已经没有抽奖次数了。',
            icon: "none",
            duration: 2000
          });
        }
      }else if (page.data.winStatus == '-1'){
        wx.showToast({
          title: '游戏已在抽奖中，请稍后。',
          icon: "none",
          duration: 2000
        });
      }
      return false;
    }

    if (!page.data.countDown){
      wx.showToast({
        title: '当前活动已结束！',
        icon: "none",
        duration: 2000
      });
      return false;
    }
    
    this.setData({
      winStatus:'-1',
      drawId:0,
      showDefault: true,
      isShowWinModal: false
    });
    let t5 = null;
    let t6 = null;
    let t7 = null;
    let t9 = null;
    let t10 = null;
    let t11 = null;
    let t1 = setTimeout(function () {
      page.getOpenAnimation(1); // 第一个动画
    }, Math.floor(Math.random()));
    let t2 = setTimeout(function(){
      page.getOpenAnimation(2); // 第二个动画
    }, Math.floor(Math.random()));
    let t3 = setTimeout(function () {
      page.getOpenAnimation(3); // 第二个动画
    }, Math.floor(Math.random()));
    let t4 = setTimeout(function(){
      t5 = setTimeout(function () {
        page.getOpenAnimation1(4); // 第一个动画
      }, Math.floor(Math.random()));
      t6 = setTimeout(function () {
        page.getOpenAnimation1(5); // 第二个动画
      }, Math.floor(Math.random()));
      t7 = setTimeout(function () {
        page.getOpenAnimation1(6); // 第二个动画
      }, Math.floor(Math.random()));
    },400);

    let t8 = setTimeout(function () {
      t9 = setTimeout(function () {
        page.getOpenAnimation2(7); // 第一个动画
      }, Math.floor(Math.random()));
      t10 = setTimeout(function () {
        page.getOpenAnimation2(8); // 第二个动画
      }, Math.floor(Math.random()));
      t11 = setTimeout(function () {
        page.getOpenAnimation2(9); // 第二个动画
      }, Math.floor(Math.random()));
    }, 800);
    
    let t12 = setTimeout(function(){
      page.startGame();
    },2000);

    page.setData({
      t1:t1,
      t2: t2,
      t3: t3,
      t4: t4,
      t5: t5,
      t6: t6,
      t7: t7,
      t8: t8,
      t9: t9,
      t10: t10,
      t11: t11,
      t12: t12,
    });
  },
  /**
   * 处理动画动作
   */
  getOpenAnimation: function (line) {
    var page = this;
    // 创建动画
    let animation = wx.createAnimation({
      duration: 850, // 执行一次动画的时间
      timingFunction: 'ease', // 动画的效果，平滑
    })

    let loop = setInterval(function () {
      if (page.data.winStatus == '-2' || page.data.winStatus == '0' || page.data.winStatus == '1'){
      // 到达预定的时间点，停止循环，将图片定位到显示区域中间位置
      animation.translateY("135%").step({
        duration: 0
      });
      handleSet(page,true);
      clearInterval(loop); // 停止循环
    } else{
        animation.translateY("280%").step().translateY(0).step({
          duration: 0
        });
      handleSet(page,false);
    }

      function handleSet(page,isEnd) {
        if (line === 1) {
          let tab1 = {};
          if (isEnd){
            if (page.data.winStatus == "1") {
              tab1.id = 0;
              tab1.url = page.data.gameResultData.imgUrls[0];
            } else if (page.data.winStatus == "0"){
              tab1.id = 0;
              tab1.url = page.data.gameResultData.imgUrls[0];
            } else if (page.data.winStatus == "-2"){
              tab1 = page.data.itemImgs[random(0, page.data.itemImgs.length)];
            }
            setTimeout(function () {
              page.setData({
                isShowWinModal: true
              });
            }, 1000);
          }else{
            tab1 = page.data.itemImgs[random(0, page.data.itemImgs.length)];
          }
          page.setData({
            tab1: tab1, // 修改显示的图片
            animationData1: animation.export()
          });
        } else if (line === 2) {
          let tab2 = {};
          if (isEnd){
            if (page.data.winStatus == "1") {
              tab2.id = 1;
              tab2.url = page.data.gameResultData.imgUrls[1];
            } else if (page.data.winStatus == "0"){
              tab2.id = 1;
              tab2.url = page.data.gameResultData.imgUrls[1];
            } else if (page.data.winStatus == "-2"){
              tab2 = page.data.itemImgs[random(0, page.data.itemImgs.length)];
            }
          }else{
            tab2 = page.data.itemImgs[random(0, page.data.itemImgs.length)];
          }
          
          page.setData({
            tab2: tab2, // 修改显示的图片
            animationData2: animation.export()
          })
        } else if (line === 3) {
          let tab3 = {};
          if (isEnd){
            if (page.data.winStatus == "1") {
              tab3.id = 2;
              tab3.url = page.data.gameResultData.imgUrls[2];
            } else if (page.data.winStatus == "0"){
              tab3.id = 2;
              tab3.url = page.data.gameResultData.imgUrls[2];
            } else if (page.data.winStatus == "-2") {
              tab3 = page.data.itemImgs[random(0, page.data.itemImgs.length)];
            }
          }else{
            tab3 = page.data.itemImgs[random(0, page.data.itemImgs.length)];
          }
          
          page.setData({
            tab3: tab3, // 修改显示的图片
            animationData3: animation.export()
          })
        } 
        
        else{
          clearInterval(loop); // 停止循环
        }
      }

      function random(lower, upper) {
        return Math.floor(Math.random() * (upper - lower)) + lower;
      }
    }, 600);
  },

  getOpenAnimation1:function(line){
    var page = this;
    // 创建动画
    let animation = wx.createAnimation({
      duration: 850, // 执行一次动画的时间
      timingFunction: 'ease', // 动画的效果，平滑
    })

    let loop = setInterval(function () {
      if (page.data.winStatus == '-2' || page.data.winStatus == '0' || page.data.winStatus == '1') {
        // 到达预定的时间点，停止循环，将图片定位到显示区域中间位置
        animation.translateY("135%").step({
          duration: 0
        });
        clearInterval(loop); // 停止循环
      } else {
        animation.translateY("280%").step().translateY(0).step({
          duration: 0
        });
        handleSet(page);
      }

      function handleSet(page) {
        if (line === 4) {
          let tab4 = {};
            tab4 = page.data.itemImgs[random(0, page.data.itemImgs.length)];
          page.setData({
            tab4: tab4, // 修改显示的图片
            animationData4: animation.export()
          });
        } else if (line === 5) {
          let tab5 = {};
          tab5 = page.data.itemImgs[random(0, page.data.itemImgs.length)];
          page.setData({
            tab5: tab5, // 修改显示的图片
            animationData5: animation.export()
          });
        } else if (line === 6) {
          let tab6 = {};
          tab6 = page.data.itemImgs[random(0, page.data.itemImgs.length)];
          page.setData({
            tab6: tab6, // 修改显示的图片
            animationData6: animation.export()
          });
        }

        else {
          clearInterval(loop); // 停止循环
        }
      }

      function random(lower, upper) {
        return Math.floor(Math.random() * (upper - lower)) + lower;
      }
    }, 600);
  },


  getOpenAnimation2: function (line) {
    var page = this;
    // 创建动画
    let animation = wx.createAnimation({
      duration: 850, // 执行一次动画的时间
      timingFunction: 'ease', // 动画的效果，平滑
    })

    let loop = setInterval(function () {
      if (page.data.winStatus == '-2' || page.data.winStatus == '0' || page.data.winStatus == '1') {
        // 到达预定的时间点，停止循环，将图片定位到显示区域中间位置
        animation.translateY("135%").step({
          duration: 0
        });
        clearInterval(loop); // 停止循环
      } else {
        animation.translateY("280%").step().translateY(0).step({
          duration: 0
        });
        handleSet(page);
      }

      function handleSet(page) {
        if (line === 7) {
          let tab7 = {};
          tab7 = page.data.itemImgs[random(0, page.data.itemImgs.length)];
          page.setData({
            tab7: tab7, // 修改显示的图片
            animationData7: animation.export()
          });
        } else if (line === 8) {
          let tab8 = {};
          tab8 = page.data.itemImgs[random(0, page.data.itemImgs.length)];
          page.setData({
            tab8: tab8, // 修改显示的图片
            animationData8: animation.export()
          });
        } else if (line === 9) {
          let tab9 = {};
          tab9 = page.data.itemImgs[random(0, page.data.itemImgs.length)];
          page.setData({
            tab9: tab9, // 修改显示的图片
            animationData9: animation.export()
          });
        }

        else {
          clearInterval(loop); // 停止循环
        }
      }

      function random(lower, upper) {
        return Math.floor(Math.random() * (upper - lower)) + lower;
      }
    }, 600);
  },
  
  gotoWinMsg:function(e){
    // 跳转到中奖信息页面
    console.log("跳转到中奖信息页面");
    let {type,id,title} = e.currentTarget.dataset
    let {gameActivityId} = this.data
    wx.navigateTo({
      url: `/subPackages3/pages/gameManage/gameList/gameList?gameActivityId=${gameActivityId}&type=0&title=${title}`
    });
  },
  createPoster:function(){
    let gameHighSetData = this.data.gameHighSetData;
    console.log("生成助力海报");
    // wx.navigateTo({
    //   url: `/subPackages/pages/housePoster/housePoster?gameActivityId=${this.data.gameActivityId}&type=4&pageName=gameIndex&posterPic=${(gameHighSetData && gameHighSetData.posterImgUrl && gameHighSetData.posterImgUrl != '') ? gameHighSetData.posterImgUrl : ''}`
    // })
    wx.navigateTo({
      url: `/subPackages/pages/housePoster/housePoster?gameActivityId=${this.data.gameActivityId}&type=4&actionType=${gameHighSetData.assistedOpening == 1?'help':''}&pageName=gameIndex&posterPic=${(gameHighSetData && gameHighSetData.posterImgUrl && gameHighSetData.posterImgUrl != '') ? gameHighSetData.posterImgUrl:''}`
    })
  },
  //邀请朋友助力
  async inviteF() {
    let pamars = {
      nickname: this.data.nickName,
      mobilePhone: this.data.mobilePhone,
      gameActivityId: this.data.gameActivityId
    }

    let { success, message } = await Serv.inviteCountServ(pamars)
    if (success) {
      
    } else {
      wx.showToast({
        title: message,
        icon: 'none'
      })
    }
  },
  onShareAppMessage: function (res) {
   
    let that = this;
    let pamars = {
      nickname: that.data.nickName,
      mobilePhone: that.data.mobilePhone,
      gameActivityId: that.data.gameActivityId
    }
    let {gameHighSetData} = this.data
    pamars = JSON.stringify(pamars)
    let shareObj = {};
    this.inviteF();
    if(app.globalData.isAddUserSuccess){
      wx.showShareMenu();
    if(gameHighSetData.allowSharing==1&&gameHighSetData.assistedOpening==0){ //可分享不可助力，分享当前活动而不是助力
      shareObj = {
        title: that.data.gameHighSetData.sharingTitle,
        path: `/subPackages3/pages/gameManage/gameTransferStation/gameTransferStation?gameActivityId=${that.data.gameActivityId}`,
        imageUrl: that.data.gameHighSetData.sharingImgUrl
      }
    }else{
      //邀请助力
      shareObj = {
         title: that.data.gameHighSetData.sharingTitle,
        path: `/subPackages3/pages/gameManage/gameTransferStation/gameTransferStation?helpPamars=${pamars}&actionType=help`,
        imageUrl: that.data.gameHighSetData.sharingImgUrl
        }
    }
    }else{
      shareObj = {
        title: that.data.gameHighSetData.sharingTitle,
        path: `/subPackages3/pages/gameManage/gameTransferStation/gameTransferStation?gameActivityId=${that.data.gameActivityId}`,
        imageUrl: that.data.gameHighSetData.sharingImgUrl
      }
    }
    return shareObj;
  },
  //活动结束倒计时
  countDown: function (){
    let that = this;
    let gameBaseData = that.data.gameBaseData;
    let nowTime = new Date(gameBaseData.nowTime.replace(/-/g, '/')).getTime();
    let endTime = new Date(gameBaseData.endTime.replace(/-/g, '/')).getTime();
    if (nowTime <= endTime){
      let time = (endTime - nowTime) / 1000;
      // 获取天、时、分、秒
      let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time % (60 * 60 * 24) / 3600);
      let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
      let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
      day = that.timeFormin(day),
      hou = that.timeFormin(hou),
      min = that.timeFormin(min),
      sec = that.timeFormin(sec)
      if(day<10){
        day = "0"+day;
      }
      if (hou < 10) {
        hou = "0" + hou;
      }
      if (min < 10) {
        min = "0" + min;
      }
      if (sec < 10) {
        sec = "0" + sec;
      }
      gameBaseData.nowTime = that.formatSecond(new Date(nowTime+1000));
      gameBaseData.day = day;
      gameBaseData.hou = hou;
      gameBaseData.min = min;
      gameBaseData.sec = sec;
      that.setData({
        gameBaseData: gameBaseData
      });
      // 每1000ms刷新一次
      if (time > 0) {
        that.setData({
          countDown: true
        })
        let djsTime = setTimeout(that.countDown, 1000);
        that.setData({
          djsTime: djsTime
        });
      } else {
        that.setData({
          countDown: false
        })
      }
    }else{
      gameBaseData.day = 0;
      gameBaseData.hou = 0;
      gameBaseData.min = 0;
      gameBaseData.sec = 0;
      that.setData({
        gameBaseData: gameBaseData,
        countDown:false
      });
    }
  },
  //小于0的格式化函数（不会出现负数）
  timeFormin:function(param) {
    return param < 0 ? 0 : param;
  },
  formatNumber:function(n){
    n = n.toString();
    return n[1] ? n : '0' + n;
  },
  // 时间格式化（每秒增加）
  formatSecond:function(date){
    let year = date.getFullYear();
    let month = date.getMonth()+1;
    let day = date.getDate();
    let hour = date.getHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();
    return [year, month, day].map(this.formatNumber).join('-') + ' ' + [hour, minute, second].map(this.formatNumber).join(':');
  },
  // async addUser() {
  //   let that = this;
  //   let { cityadcode } = app.globalData.cityData;
  //   let pamars = {
  //     nickname: this.data.nickName,
  //     mobilePhone: this.data.mobilePhone,
  //     headPortraitUrl: this.data.headPortraitUrl,
  //     gameActivityId: this.data.gameActivityId,
  //     cityCode: cityadcode
  //   }
  //   let { success, result } = await Serv.addUserServ(pamars);
  //   console.log(success);
  //   if(success){
  //     //获取当前用户信息
  //     that.getActivityUser();
  //   }
  // },
  //获取基础设置的数据
  async getBaseData(){
    let that = this;
    let params = {
      gameActivityId: that.data.gameActivityId
    }; 
    let { success, result } = await Serv.getDetail(params);
    console.log(result);
    if(success){
      if(result){
        let gameBaseData = that.data.gameBaseData;
        let tab1 = that.data.tab1;
        let tab2 = that.data.tab2;
        let tab3 = that.data.tab3;
        // let tab4 = that.data.tab4;
        if (result.noPrizeImgUrls && result.noPrizeImgUrls != ""){
          result.noPrizeImgUrls = result.noPrizeImgUrls.substring(1, result.noPrizeImgUrls.length - 1);
          result.noPrizeImgUrls = result.noPrizeImgUrls.split(",");
          tab1.url = result.noPrizeImgUrls[0].substring(1, result.noPrizeImgUrls[0].length - 1);
          tab2.url = result.noPrizeImgUrls[1].substring(1, result.noPrizeImgUrls[1].length - 1);
          tab3.url = result.noPrizeImgUrls[2].substring(1, result.noPrizeImgUrls[2].length - 1);
          // tab4.url = result.noPrizeImgUrls[3].substring(1, result.noPrizeImgUrls[3].length - 1);
        }
        let itemImgs = [];
        if (result.noPrizeImgUrls != null && result.noPrizeImgUrls.length > 0) {
          for (let i = 0; i < result.noPrizeImgUrls.length;i++){
            let m={
              id:(i+1),
              url: result.noPrizeImgUrls[i].substring(1, result.noPrizeImgUrls[i].length-1)
            };
            itemImgs.push(m);
          }
        }
        gameBaseData = result;
        gameBaseData.nowTime = result.currentTime;
        gameBaseData.endTime = result.endTime;
        that.setData({
          gameBaseData: gameBaseData,
          itemImgs: itemImgs,
          tab1: tab1,
          tab2: tab2,
          tab3: tab3
          // tab4: tab4
        });
        that.houseRecommend();
        setTimeout(function(){
          that.countDown();
        },500);
      }
    }
  },
  //获取高级设置的数据
  async getHighSetData() {
    let that = this;
    let params = {
      gameActivityId: that.data.gameActivityId
    };
    let { success, result } = await Serv.getHighSetData(params);
    console.log(result);
    if (success) {
      if (result) {
        that.setData({
          gameHighSetData: result
        });
        that.preload();
      }
    }
  },
  //获取当前活动中奖信息列表
  async getWinnerUserList(){
    let that = this;
    let params = {
      gameActivityId: that.data.gameActivityId
    }; 
    let { success, result } = await Serv.getWinnerUserList(params);
    that.scrolltxt();
    if(success){
      if(result){
        if (result.records.length > 0){
          that.setData({
            winnersData: result.records
          });
          that.scrolltxt();
        }
      }
    }
  },
  //获取当前用户的信息
  async getActivityUser(){
    let that = this;
    let params = {
      gameActivityId: that.data.gameActivityId,
      mobilePhone: that.data.mobilePhone
    };
    let { success, result } = await Serv.getActivityUser(params);
    console.log(result);
    if(success){
      if(result){
        let drawId = 0;
        if (result.luckDrawFlag != 0 && result.remainLuckDrawNumber > 0){
          drawId = 1;
        }
        that.setData({
          activityUser:result,
          drawId: drawId
        });
      }
    }
  },
  //开始游戏
  async startGame(){
    let that = this;
    let params = {
      gameActivityId: that.data.gameActivityId,
      mobilePhone: that.data.mobilePhone,
      gameActivityUserId:that.data.activityUser.id
    };
    let { success, result,message } = await Serv.startGame(params);
    
    if(success){
      if(result){
        if (result.imgUrls && result.imgUrls != ""){
          result.imgUrls = JSON.parse(result.imgUrls);
        }
        that.setData({
          gameResultData:result
        });
        setTimeout(function(){
          if (result.prizeFlag == 1) {
            that.getWin();
            //获取游戏中奖后的奖品信息
            that.getDetailByPrizeId();
          } else {
            that.getNoWin();
          }
        },2000);
      }
    }else{
      let that = this;
      wx.showToast({
        title: message,
        icon: 'none'
      })
      that.setData({
        winStatus: '-2'
      });
      

    }
  },
  async getDetailByPrizeId(){
    let that = this;
    let params = {
      prizeId: that.data.gameResultData.prizeId
    };
    let { success, result } = await Serv.getDetailByPrizeId(params);
    if(success){
      if(result){
        that.setData({
          gamePrizeData:result
        });
      }
    }
  },
  async houseRecommend(){
    let that = this;
    let params = {};
    console.log(that.data.gameBaseData);
    if (that.data.gameBaseData.type == "1"){
      params = {
        productIds: that.data.gameBaseData.productId
      }
    }else{
      let { cityadcode } = app.globalData.cityData;
      params = {
        city: cityadcode
      }
    }
    let { success, rows } = await Serv.houseRecommend(params);
    if(success){
      if (rows){
        rows.map(item => {
          if (item.tags && item.tags.length > 3) {
            item.tags = item.tags.slice(0, 3)
          }
        })
        that.setData({
          recommendData: rows
        });
      }
    }
  },
  // //点击取消领取奖品提示
  // prizeTipCancel:function(){
  //   this.setData({
  //     showPrizeTipModal: false
  //   });
  // },
  // //点击确定领取奖品提示
  // prizeTipConfirm:function(){
  //   this.setData({
  //     showPrizeTipModal: false
  //   });
  //   if (this.data.gamePrizeData.rewardWay == '2'){
  //     wx.navigateTo({
  //       url: `/subPackages/pages/address/addressList/addressList?type=game&prizeId=${this.data.gameResultData.prizeId}`
  //     });
  //   }
  // },
  //领取奖品的时候提示
  openPrizeModal(e) {
    let {type,id,title} = e.currentTarget.dataset
    // let that = this;
    // that.setData({
    //   showPrizeTipModal:true
    // });
    // if (this.data.gamePrizeData.rewardWay == '2') {
      wx.navigateTo({
        url: `/subPackages3/pages/gameManage/gameList/gameList?type=0&&gameActivityId=${this.data.gameActivityId}&title=${title}&isShow=1`
      });
    // }
  },
})